﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Jack.RedisLib;

using Youshow.Ace.DependencyInjection;

namespace JackProjectTemplate.Cache.DistributedIdentifyGeneraters.SequentialGuid
{
    public class IdGeneratorService(IRedisClient redisClient, IIdGenerator idGenerator) : IScopedDependency
    {
        private readonly IRedisClient _redisClient = redisClient;
        private readonly IIdGenerator _idGenerator = idGenerator;

        public async Task<string> NewId(string prefix)
        {
            string newId = $"{prefix}{_idGenerator.NewId():n}";

            string key = $"{newId}:_NewId_";
            if (await _redisClient.StringIncrement(key, 1) == 1)
            {
                await _redisClient.KeyExpire(key, TimeSpan.FromSeconds(3));
                return newId;
            }

            return await NewId(prefix);
        }
    }
}
